package com.itheima.wechat;

import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfo;
import com.itheima.service.OrderService;
import com.itheima.utils.JedisUtl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    JedisUtl jedisUtl;

    @Reference
    OrderService orderService;

    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderInfo orderInfo){
        String token = orderInfo.getToken();
        if(token == null){
            return Result.ERROR("非法请求");
        }

        Long del = jedisUtl.del(token);//redi是单线程，所有的请求来了之后都要排队执行删除，那肯定只有一个哥们能够删除成功
        if(del == 0){//del = 0 没有删除成功  del= 1 删除成功
            return Result.ERROR("重复请求");
        }

        //校验用户输入的验证码
        String validateCode = orderInfo.getValidateCode();
        String telephone = orderInfo.getTelephone();

        String redisCode = jedisUtl.get(telephone + RedisConstant.SMS_CODE_KEY_ORDER);

        if(redisCode == null || !redisCode.equals(validateCode)){
            //正常的程序异常逻辑处理
            jedisUtl.setex(token,60 * 15 ,token);
            return Result.ERROR("验证码输入错误");
        }
        //把预约类型设置为微信预约
        orderInfo.setOrderType(Order.ORDERTYPE_WEIXIN);

        Result result = null;
        try {
            result = orderService.submit(orderInfo);
        } catch (OptimisticLockingFailureException e) {
            int max = 15;
            while (max > 0) {
                try {
                    result = orderService.submit(orderInfo);
                    return  result;
                } catch (OptimisticLockingFailureException ex) {
                    ex.printStackTrace();
                    max --;

                    if(max==0){
                        System.out.println("重试"+max+"次还不行：" + JSON.toJSONString(orderInfo));
                    }
                }
            }



        }

        //下单成功之后可以发个短信提示：恭喜你预约成功，请于2020-04-25早上。。。。到医院体检

        return result;

    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        Map map = orderService.findById(id);
        return Result.OK("",map);
    }

    @RequestMapping("/getToken")
    public Result getToken(){
        String token = UUID.randomUUID().toString();

        jedisUtl.setex(token,60 * 15,token);

        return Result.OK("",token);
    }
}
